package com.nercel.dsj.gksales.interceptor;


import com.nercel.dsj.gksales.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalAccessInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(GlobalAccessInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		String ip = IpUtil.getIpAddr(request);
		String url = "[" + request.getMethod() + "] " + request.getRequestURI() + "?" + (request.getQueryString() == null ? "" : request.getQueryString());
		logger.info("IP: "+ ip +" -- [" + url + "]");
		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//	    PerformanceMonitor.end();
		super.afterCompletion(request, response, handler, ex);
	}


	@Override
	public void postHandle(HttpServletRequest request,
						   HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {
		long startTime = (Long) request.getAttribute("startTime");
		long endTime = System.currentTimeMillis();
		long executeTime = endTime - startTime;
		String ip = IpUtil.getIpAddr(request);
		String url = "[" + request.getMethod() + "] " + request.getRequestURI() + "?" + (request.getQueryString() == null ? "" : request.getQueryString());
		logger.info("IP: "+ ip +" -- 耗时:" + executeTime + "ms -- [" + url + "]");
		super.postHandle(request, response, handler, modelAndView);
	}

}
